class RecordResult < ActiveRecord::Base
  validates :name, presence: true

  # 条目数量
  ScoreCountMap = [8, 8, 7, 8, 8, 7, 7, 7, 7].freeze

  # 体质结果
  ConstitutionResult = {yes: '是', almost_yes: '倾向是', no: '否'}.freeze
  TendencyType = ['平和体质', '气虚型体质', '阳虚型体质',
                  '阴虚型体质', '痰湿型体质', '湿热型体质',
                  '血瘀型体质', '气郁型体质', '禀型体质'].freeze


  (1..9).each do |index|
    score = "score" + index.to_s
    real_score = "real_" + score

    # 转化分数
    define_method real_score.to_sym do
      (self.send(score.to_sym).to_i - ScoreCountMap[index - 1]) / (ScoreCountMap[index - 1] * 4).to_f * 100
    end

    # 体质测试
    constitution = "constitution_" + score

    define_method constitution.to_sym do
      score_count = self.send(real_score.to_sym)
      # 平和体质测试
      if index == 1
        if score_count >= 60 && (2..9).all? { |i| self.send("real_score" + i.to_s) < 30 }
          :yes
        elsif score_count >= 60 && (2..9).all? { |i| self.send("real_score" + i.to_s) < 40 }
          :almost_yes
        else
          :no
        end
      # 偏颇体质测试
      else
        if score_count >= 40
          :yes
        elsif score_count >= 30 && score_count <= 39
          :almost_yes
        else
          :no
        end
      end
    end
  end

  def score_result
    tendency_arr = []

    case constitution_score1
    when :yes
      line1 = "您的体质类型是平和质"
    when :almost_yes
      line1 = "您的体质类型是平和质"
      tendency_arr << find_tendency_type
    else
      line1 = "您的体质类型不是平和质"
      tendency_arr << find_tendency_type
    end

    result = <<-Html
      #{line1}
      <br />
      您的体质类型倾向是：#{tendency_arr.join(', ')}
    Html

    result.html_safe
  end

  private

  def find_tendency_type
    (2..9).select do |i|
      self.send("constitution_score" + i.to_s) == :almost_yes
    end.map { |i| TendencyType[i - 1] }
  end
end
